package system

import (
	"MoSkeleton/framework/core/models"
	"MoSkeleton/models/base"
	"errors"
	"gorm.io/gorm"
)

type SysDictData struct {
	models.MoModel
	DictSort  int32  `gorm:"column:dict_sort;type:INT;"`
	DictLabel string `gorm:"column:dict_label;type:VARCHAR(100);"`
	DictValue string `gorm:"column:dict_value;type:VARCHAR(100);"`
	DictType  string `gorm:"column:dict_type;type:VARCHAR(100);"`
	CssClass  string `gorm:"column:css_class;type:VARCHAR(100);"`
	ListClass string `gorm:"column:list_class;type:VARCHAR(100);"`
	IsDefault string `gorm:"column:is_default;type:CHAR(1);"`
	Status    string `gorm:"column:status;type:CHAR(1);"`
	CreatedBy string `gorm:"column:created_by;type:VARCHAR(64);"`

	UpdatedBy string `gorm:"column:updated_by;type:VARCHAR(32);"`
	Remark    string `gorm:"column:remark;type:VARCHAR(500);"`
}

func (d *SysDictData) TableName() string {
	return "sys_dict_data"
}

func (d *SysDictData) UpdateDictDataType(tx *gorm.DB, old, new string) (int64, error) {
	result := base.GetModelDB(tx).Model(&SysDictData{}).Where("dict_type = ?", old).Update("dict_type", new)
	return result.RowsAffected, result.Error
}

func (d *SysDictData) UpdateDictDataById(tx *gorm.DB) error {
	return base.GetModelDB(tx).Save(d).Error
}

func (d *SysDictData) GetFirstByDictTypes(dictTypes *[]string) (*SysDictData, error) {
	dictData := &SysDictData{}
	result := base.GetModelDB(nil).Model(&SysDictData{}).Where("dict_type in (?)", *dictTypes).First(dictData)
	if result.Error != nil {
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		return nil, result.Error
	}
	return dictData, nil
}
